/**
 * 通过 flag 控制日志级别
 */
import registerGlobal from '@gnlab/utils/env-browser/global'
import storages from '@gnlab/utils/env-browser/storages'
import { LogLevel, logger as rootLogger, adaptDebugLib } from '@gnlab/utils/logging'
import debugLib from 'debug'

export type LoggingFlags = {
  level: LogLevel // 日志级别
  levelName: string // 日志级别名称
  thirdParty: string // 开启哪些三方库的日志（传给 debug 工具）。空字符串为屏蔽一切，* 为开启一切
}

const defaultFlags = {
  level: LogLevel.Warning,
  levelName: LogLevel[LogLevel.Warning],
  thirdParty: '',
}

let flags: LoggingFlags | undefined
export function getFlags() {
  if (!flags) {
    flags = storages.local.get('quntool-logging', defaultFlags) as LoggingFlags
  }
  return flags
}

export function setFlags(_flags: LoggingFlags) {
  flags = _flags
  storages.local.set('quntool-logging', flags)
  applyFlags()
}

export function applyFlags() {
  const flags = getFlags()
  rootLogger.setLevel(flags.level)
  if (flags.thirdParty) {
    adaptDebugLib(debugLib, flags.thirdParty)
  }
}

/**
 * 提供一个全局变量入口，便于调试
 */
registerGlobal('logging', {
  get flags() {
    return getFlags()
  },
  switchDebug() {
    const flags = getFlags()
    const level = flags.level === LogLevel.Debug ? LogLevel.Warning : LogLevel.Debug
    setFlags({
      ...flags,
      level,
      levelName: LogLevel[level],
    })
  },
  switchThirdParty() {
    const flags = getFlags()
    setFlags({
      ...flags,
      thirdParty: flags.thirdParty === '' ? '*' : '',
    })
  },
})
